const express = require('express');
const router = express.Router();
const douyinService = require('../services/douyinService');
const weiboService = require('../services/weiboService');
const zhihuService = require('../services/zhihuService');
const baiduService = require('../services/baiduService');
const mockWeiboService = require('../services/mockWeiboService');
const apiHealthChecker = require('../utils/apiHealthChecker');
const WeiboDataValidator = require('../utils/weiboDataValidator');
const { rateLimitMiddleware, apiKeyAuth } = require('../middleware/rateLimit');

// 获取热搜列表
router.get('/', rateLimitMiddleware, apiKeyAuth, async (req, res) => {
  try {
    const { platform, useMock } = req.query;
    
    let data;
    let dataReport = null;
    
    if (platform === '微博' || platform === 'weibo' || !platform) {
      // 微博平台 - 优先使用真实数据，集成数据验证
      try {
        console.log('🔄 获取微博数据并进行质量验证...');
        data = await weiboService.getHotSearch();
        
        if (data && data.length > 0) {
          // 使用WeiboDataValidator验证和清洗数据
          dataReport = WeiboDataValidator.generateReport(data);
          data = dataReport.cleanedData; // 使用清洗后的数据
          
          console.log(`📊 微博数据质量报告:`);
          console.log(`- 总数据: ${dataReport.summary.totalItems}`);
          console.log(`- 有效数据: ${dataReport.summary.validItems}`);
          console.log(`- 数据质量: ${dataReport.summary.dataQuality}`);
          console.log(`- 真实数据比例: ${dataReport.summary.realDataRatio}`);
          console.log(`- 是否为真实数据: ${dataReport.summary.isRealData ? '是' : '否'}`);
          
          // 如果数据质量不达标，记录警告
          if (!dataReport.details.quality.isValid) {
            console.warn('⚠️ 数据质量警告:', dataReport.details.quality.reason);
          }
        }
        
        if (!data || data.length === 0) {
          console.warn('❌ 微博服务返回空数据，使用模拟数据');
          data = await mockWeiboService.getHotSearch();
        }
      } catch (error) {
        console.warn('❌ 微博API失败，使用模拟数据:', error.message);
        data = await mockWeiboService.getHotSearch();
      }
    } else if (platform === '抖音' || platform === 'douyin') {
      // 抖音平台
      try {
        data = await douyinService.getHotSearch();
      } catch (error) {
        console.warn('Douyin API failed, falling back to mock data:', error.message);
        data = await mockWeiboService.getHotSearch();
      }
    } else if (platform === '知乎' || platform === 'zhihu') {
      // 知乎平台
      data = await zhihuService.getHotSearch();
    } else if (platform === '百度' || platform === 'baidu') {
      // 百度平台
      data = await baiduService.getHotSearch();
    } else {
      // 其他平台可以在这里扩展
      data = [];
    }

    // 构建响应数据，包含数据质量信息
    const response = {
      success: true,
      data: data,
      total: data.length,
      timestamp: new Date().toISOString()
    };
    
    // 如果有数据报告，添加到响应中（开发模式下）
    if (dataReport && process.env.NODE_ENV !== 'production') {
      response.dataQuality = dataReport.summary;
    }
    
    // 添加数据源标识
    if (data && data.length > 0 && data[0].source) {
      response.dataSource = {
        primary: data[0].source,
        isRealData: dataReport ? dataReport.summary.isRealData : false,
        timestamp: new Date().toISOString()
      };
    }

    res.json(response);
  } catch (error) {
    console.error('❌ 获取热点数据错误:', error);
    res.status(500).json({
      success: false,
      error: error.message || '获取热点数据失败',
      data: []
    });
  }
});

// 获取热搜详情
router.get('/:id', rateLimitMiddleware, apiKeyAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const { useMock } = req.query;
    
    let data;
    if (id.startsWith('weibo_')) {
      // 微博热点
      if (useMock !== 'false') {
        data = await mockWeiboService.getHotspotDetail(id);
      } else {
        try {
          data = await weiboService.getHotspotDetail(id);
        } catch (error) {
          console.warn('Weibo API failed, falling back to mock data:', error.message);
          data = await mockWeiboService.getHotspotDetail(id);
        }
      }
    } else if (id.startsWith('douyin_')) {
      // 抖音热点
      if (useMock !== 'false') {
        data = await mockWeiboService.getHotspotDetail(id);
      } else {
        try {
          data = await douyinService.getHotspotDetail(id);
        } catch (error) {
          console.warn('Douyin API failed, falling back to mock data:', error.message);
          data = await mockWeiboService.getHotspotDetail(id);
        }
      }
    } else if (id.startsWith('zhihu_')) {
      // 知乎热点
      data = await zhihuService.getHotspotDetail(id);
    } else if (id.startsWith('baidu_')) {
      // 百度热点
      data = await baiduService.getHotspotDetail(id);
    } else {
      return res.status(404).json({
        success: false,
        error: '热点不存在'
      });
    }
    
    res.json({
      success: true,
      data: data,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Get hotspot detail error:', error);
    res.status(error.message.includes('不存在') ? 404 : 500).json({
      success: false,
      error: error.message || '获取热点详情失败'
    });
  }
});

// 搜索热搜
router.get('/search/:query', rateLimitMiddleware, apiKeyAuth, async (req, res) => {
  try {
    const { query } = req.params;
    const { platforms, useMock } = req.query;
    
    if (!query) {
      return res.json({
        success: true,
        data: [],
        total: 0,
        timestamp: new Date().toISOString()
      });
    }

    let allData;
    if (useMock !== 'false') {
      allData = await mockWeiboService.getHotSearch();
    } else {
      try {
        allData = await weiboService.getHotSearch();
      } catch (error) {
        console.warn('Weibo API failed, falling back to mock data:', error.message);
        allData = await mockWeiboService.getHotSearch();
      }
    }
    
    // 关键词搜索
    const searchResults = allData.filter(item => 
      item.title.includes(query) || 
      item.description.includes(query) ||
      item.tags.some(tag => tag.includes(query))
    );

    // 平台筛选
    let filteredResults = searchResults;
    if (platforms) {
      const platformList = platforms.split(',');
      filteredResults = searchResults.filter(item => 
        platformList.includes(item.platform)
      );
    }

    res.json({
      success: true,
      data: filteredResults,
      total: filteredResults.length,
      query: query,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Search hotspots error:', error);
    res.status(500).json({
      success: false,
      error: error.message || '搜索失败',
      data: []
    });
  }
});

// 获取平台列表
router.get('/platforms/list', rateLimitMiddleware, apiKeyAuth, (req, res) => {
  res.json({
    success: true,
    data: ['微博', '抖音', '知乎', '百度'], // 支持微博、抖音、知乎和百度
    timestamp: new Date().toISOString()
  });
});

// 健康检查
router.get('/health/check', (req, res) => {
  res.json({
    success: true,
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 缓存状态
router.get('/cache/status', apiKeyAuth, async (req, res) => {
  try {
    const redis = require('../config/redis');
    const cacheExists = await redis.exists('weibo:hotsearch');
    
    res.json({
      success: true,
      cached: cacheExists,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 清除缓存
router.delete('/cache/clear', apiKeyAuth, async (req, res) => {
  try {
    const redis = require('../config/redis');
    await redis.del('weibo:hotsearch');
    
    res.json({
      success: true,
      message: '缓存已清除',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// API健康状态监控
router.get('/health/api-status', apiKeyAuth, async (req, res) => {
  try {
    const healthReport = apiHealthChecker.getHealthReport();
    const summary = {
      totalApis: Object.keys(healthReport).length,
      healthyApis: Object.values(healthReport).filter(api => api.healthy).length,
      unhealthyApis: Object.values(healthReport).filter(api => !api.healthy).length
    };
    
    res.json({
      success: true,
      summary,
      details: healthReport,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// 清除API健康检查缓存
router.delete('/health/api-cache', apiKeyAuth, async (req, res) => {
  try {
    apiHealthChecker.clearCache();
    
    res.json({
      success: true,
      message: 'API健康检查缓存已清除',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;